package com.gusti.admincasa.client.udp;

import java.awt.TrayIcon;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Date;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.gusti.admincasa.client.dto.MessageDto;
import com.gusti.admincasa.client.util.AdminCasaClientUtil;
import com.gusti.admincasa.client.util.DataUDP;
import com.gusti.admincasa.client.util.DateUtil;
import com.gusti.admincasa.client.util.Debug;
import com.gusti.admincasa.client.util.TrayIconViewer;

/**
 * 
 * @author gusti
 *
 */
public class ClientUDPThread extends Thread {

	private DataUDP data;

	public ClientUDPThread( DataUDP data ) {
		super( "ClientUDPThread" );
		Debug.log( "Client thread started" );
		this.data = data;
		TrayIconViewer.getInstance();
	}

	@Override
	public void run() {

		int threadSleep = AdminCasaClientUtil.getThreadSleep();
		while( true ) {
			try {

				Debug.log( "Sending data..." );
				processData();
				Thread.sleep( threadSleep );

			} catch (InterruptedException e) {
				Debug.error( e );
				continue;
			}
		}

	}

	private void processData() throws InterruptedException {

		try {

			data.setTimeStamp( String.valueOf( new Date().getTime() ) );

			Gson gson = new Gson();
			String json = gson.toJson( data );

			// {"uuid":"1331077789335","userName":"gusti","computerName":"gusti-dominio-local","timeStamp":"1331077843644"}
			String request = AdminCasaClientUtil.getServerUrl() + "admincasa/rest/iamhere/" + json;
			URL url = new URL( request );
			InputStreamReader inputStreamReader = new InputStreamReader( url.openStream() );
			BufferedReader bufferedReader = new BufferedReader( inputStreamReader );
			JsonElement response = gson.fromJson( bufferedReader, JsonElement.class );

			String errorMsg = "";
			if( !response.getAsJsonObject().get("errorMsg").isJsonNull() ) {
				errorMsg = response.getAsJsonObject().get("errorMsg").getAsString();
			}
			JsonElement data = response.getAsJsonObject().get("data");
			if( !data.isJsonNull() ) {
				JsonArray dataArray = response.getAsJsonObject().get("data").getAsJsonArray();
				for (JsonElement jsonElement : dataArray) {
					int id = jsonElement.getAsJsonObject().get("id").getAsInt();
					String message = jsonElement.getAsJsonObject().get("message").getAsString();
					String sendDate = DateUtil.getDateTime( DateUtil.getDateFromTimeStamp( jsonElement.getAsJsonObject().get("sendDate").getAsLong() ) );
					int ownerUserId = jsonElement.getAsJsonObject().get("owner").getAsJsonObject().get("id").getAsInt();
					String senderUserName = "sistema";
					if( !jsonElement.getAsJsonObject().get("sender").isJsonNull() ) {
						senderUserName = jsonElement.getAsJsonObject().get("sender").getAsJsonObject().get("name").getAsString();
					}
					TrayIconViewer.getInstance().addMessages( id, new MessageDto( id, errorMsg, message, ownerUserId, sendDate, senderUserName ) );
					TrayIconViewer.getInstance().displayMessage( "Nuevo mensaje de " + senderUserName, "Click aqui para verlo", TrayIcon.MessageType.INFO );
				}
			}
		} catch (MalformedURLException e) {
			Debug.error( e );
		} catch (IOException e) {
			Debug.error( e );
		}

	}

}
